<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Twitter HTTP Post Controller
 *
 * PHP version 5
 * LICENSE: This source file is subject to AGPL license 
 * that is available through the world-wide-web at the following URI:
 * http://www.gnu.org/licenses/agpl.html
 * @author	   Omar Vega Ramos <ovruni@gnu.org.pe> 
 * @copyright      (c) 2013 - 2016 Omar Vega Ramos
 * @license	   http://www.gnu.org/licenses/agpl.html GNU Affero General Public License (AGPL) 
 */

class Twitter_Controller extends Controller {
  
  public function __construct()
  {
    parent::__construct();
    
    // If user doesn't have access, redirect to login
    if (!$this->auth->has_permission('admin_ui')) {
      url::redirect(url::site('login'));
    }
  }
  
  public function index()
  {
    // Retrieve Current Settings
    $twitter = ORM::factory('twitter', 1);
    
    if (($twitter->consumer_key == '') OR ($twitter->consumer_secret == '')) {
      echo 'Need set Consumer key and Consumer secret.<br>'.
           'Please go to Twitter Apps page '.html::anchor('https://dev.twitter.com/apps/new').' and create an application.<br>'.
           'The Callback URL must be '.html::anchor(url::site('twitter')).' and make sure the application you create has write permissions';
      header('Refresh: 15; URL='.url::site('admin/twitter_settings'));
      return;
    }
    
    $client = new Oauth_client_class;
    $client->debug = 1;
    $client->server = '';
    $client->oauth_version = '1.0';
    $client->request_token_url = 'https://api.twitter.com/oauth/request_token';
    $client->dialog_url = 'https://api.twitter.com/oauth/authorize';
    $client->access_token_url = 'https://api.twitter.com/oauth/access_token';
    $client->url_parameters = FALSE;
    $client->authorization_header = TRUE;
    $client->redirect_uri = url::site('twitter');
    $client->client_id = $twitter->consumer_key;
    $client->client_secret = $twitter->consumer_secret;
    
    if (($success = $client->Initialize())) {
      if (($success = $client->Process())) {
	if (strlen($client->access_token)) {
	  $twitter->oauth_token = $client->access_token;
	  $twitter->oauth_token_secret = $client->access_token_secret;
	  $twitter->save();
	}
      }
      
      $success = $client->Finalize($success);
    }
    
    if ($client->exit)
      $output = 'Could not connect to Twitter. Refresh the page or try again later.';
    
    if ($success) {
      $output = 'You are now authenticated to Twitter';
    }
    
    echo $output;
    header('Refresh: 5; URL='.url::site('admin/twitter_settings'));
  }
}
